<?php

namespace app\controller\admin\sgz;

use app\model\admin\sgz\SgzBattle;
use app\model\admin\sgz\SgzBattleTeam;
use app\model\admin\sgz\SgzGenerals;
use app\model\admin\sgz\SgzTeam;
use app\model\admin\sgz\SgzTeamGenerals;
use app\model\admin\sgz\SgzTeamGeneralsDetail;
use app\model\admin\sgz\SgzWarMethods;
use app\model\admin\sgz\SgzWarMethodsGenerals;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Team extends Backend
{
    protected $model;
    public $orderRule = ['id' => 'DESC'];
    protected $noNeedAuth = ['*'];

    public function initialize()
    {
        $this->model = new SgzTeam();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');

        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->cache(true)->with(["teamGenerals","user"])->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                if($item['user']!=null){
                    $item['user_name'] = $item['user']['nickname'];
                }
                $i = 0;
                foreach ($item['teamGenerals'] as $it) {
                    if ($it['pivot']['position'] == 1) {
                        $item['master'] = $it['name'];
                    } elseif ($it['pivot']['position'] == 2) {
                        if ($i == 0) {
                            //按顺序第一个是主将 第二个是副将1  第三个是副将2
                            $item['one_generals'] = $it['name'];
                            $i++;
                        } else {
                            $item['two_generals'] = $it['name'];
                        }
                    }
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = $this->request->post();
        try {

            $create_time = date("Y-m-d H:i:s");
            $data = [
                'season' => $post['season'],
                'title' => $post['title'],
                'user_id' => $post['user_id'],
                'job' => $post['job'],
                'right_range' => $post['right_range'],
                'arms' => $post['arms'],
                'description' => $post['description'],
                'imgs' => $post['imgs'],
                'create_time' => $create_time,
                'update_time' => $create_time,
            ];
            Db::startTrans();
            $id = $this->model->insertGetId($data);
            $generalsList = [];
            $generalsDetailList = [];
            $generalsIds = [];
            foreach ($post['generals'] as $item) {
                $result = $item['force'] + $item['intelligence'] + $item['commander'] + $item['speed'];
                if ($result > 50) {
                    return $this->error("分配点数不能超过50点");
                }
                if(in_array($item['generals_id'],$generalsIds)){
                    return $this->error("主将和副将不能相同");
                }
                array_push($generalsIds,$item['generals_id']);
                $generalsList[] = [
                    'team_id' => $id,
                    'generals_id' => $item['generals_id'],
                    'position' => $item['position'],
                    'force' => $item['force'],
                    'intelligence' => $item['intelligence'],
                    'commander' => $item['commander'],
                    'speed' => $item['speed'],
                    'create_time' => $create_time,
                ];
                if (isset($item['warMethods'])) {
                    if(count($item['warMethods'])>2){
                        return $this->error("武将战法最多只能选两个");
                    }
                    foreach ($item['warMethods'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 1,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
                if (isset($item['bigBook'])&&$post['season']!="S1") {
                    if(count($item['bigBook'])>1){
                        return $this->error("武将大兵书最多只能选1个");
                    }
                    foreach ($item['bigBook'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 2,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
                if (isset($item['smallBook'])&&$post['season']!="S1") {
                    if(count($item['smallBook'])>1&&$post['season']=="S2"){
                        return $this->error("武将小兵书最多只能选1个");
                    }
                    if(count($item['smallBook'])>2){
                        return $this->error("武将小兵书最多只能选2个");
                    }
                    foreach ($item['smallBook'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 3,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
            }
            if (count($generalsList) > 0) (new SgzTeamGenerals())->insertAll($generalsList);
            if (count($generalsDetailList) > 0) (new SgzTeamGeneralsDetail())->insertAll($generalsDetailList);
            Db::commit();
            $this->clearCache();
            return $this->success('添加成功', $post);
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $post = $this->request->post();
        try {
            $create_time = date("Y-m-d H:i:s");
            $data = [
                'id' => $post['id'],
                'user_id' => $post['user_id'],
                'season' => $post['season'],
                'title' => $post['title'],
                'job' => $post['job'],
                'right_range' => $post['right_range'],
                'arms' => $post['arms'],
                'description' => $post['description'],
                'imgs' => $post['imgs'],
//                'create_time' => $create_time,
                'update_time' => $create_time,
            ];
            Db::startTrans();
            $this->model->update($data);
            $id = $post['id'];
            $generalsList = [];
            $generalsDetailList = [];
            $generalsIds = [];
            foreach ($post['generals'] as $item) {
                $result = $item['force'] + $item['intelligence'] + $item['commander'] + $item['speed'];
                if ($result > 50) {
                    return $this->error("分配点数不能超过50点");
                }
                if(in_array($item['generals_id'],$generalsIds)){
                    return $this->error("主将和副将不能相同");
                }
                array_push($generalsIds,$item['generals_id']);
                $generalsList[] = [
                    'team_id' => $id,
                    'generals_id' => $item['generals_id'],
                    'position' => $item['position'],
                    'force' => $item['force'],
                    'intelligence' => $item['intelligence'],
                    'commander' => $item['commander'],
                    'speed' => $item['speed'],
                    'create_time' => $create_time,
                ];
                if (isset($item['warMethods'])) {
                    if(count($item['warMethods'])>2){
                        return $this->error("武将战法最多只能选两个");
                    }
                    foreach ($item['warMethods'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 1,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
                if (isset($item['bigBook'])&&$post['season']!="S1") {
                    if(count($item['bigBook'])>1){
                        return $this->error("武将大兵书最多只能选1个");
                    }
                    foreach ($item['bigBook'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 2,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
                if (isset($item['smallBook'])&&$post['season']!="S1") {
                    if(count($item['smallBook'])>1&&$post['season']=="S2"){
                        return $this->error("武将小兵书最多只能选1个");
                    }
                    if(count($item['smallBook'])>2){
                        return $this->error("武将小兵书最多只能选2个");
                    }
                    foreach ($item['smallBook'] as $it) {
                        $generalsDetailList[] = [
                            'team_id' => $id,
                            'team_generals_id' => $item['generals_id'],
                            'type' => 3,
                            'relation_id' => $it,
                            'create_time' => $create_time,
                        ];
                    }
                }
            }
            Db::name("sgz_team_generals")->where('team_id',$id)->delete();
            Db::name("sgz_team_generals_detail")->where('team_id',$id)->delete();
            if (count($generalsList) > 0) (new SgzTeamGenerals())->insertAll($generalsList);
            if (count($generalsDetailList) > 0) (new SgzTeamGeneralsDetail())->insertAll($generalsDetailList);
            Db::commit();
            $this->clearCache();
            return $this->success('编辑成功', $post);
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //查看详情
    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        $info->imgs = explode(",", $info->imgs);
        if (is_object($info)) $info = $info->toArray();
        $generals = (new SgzTeamGenerals())->where('team_id', $id)->select()->toArray();
        $generals = array_combine(array_column($generals, "generals_id"), $generals);
        $generalsDetail = (new SgzTeamGeneralsDetail())->where('team_id', $id)->select()->toArray();
        foreach ($generalsDetail as $item) {
            switch ($item['type']) {
                case 1:
                    $generals[$item['team_generals_id']]['warMethods'][] = $item['relation_id'];
                    break;
                case 2:
                    $generals[$item['team_generals_id']]['bigBook'][] = $item['relation_id'];
                    break;
                case 3:
                    $generals[$item['team_generals_id']]['smallBook'][] = $item['relation_id'];
                    break;
            }
        }
        $generals = array_values($generals);
        return $this->success('获取成功', compact("info", "generals"));
    }

    //设置展示
    public function setIsShow()
    {
        $id = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['is_show'] = $fieldVal;

        try {
            if ($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //设置点赞
    public function setNumber()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['like_num'] = $fieldVal;

        try {
            if($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }
}